import React, { useState, useEffect, useRef } from 'react';
import { Modal, Tree, Form, Select, DatePicker, Space, Button, Spin, message, Pagination, Input } from 'antd';
import type { DataNode } from 'antd/es/tree';
import DraggableTable from '@/components/DraggableTable';
import request from '@/utils/request';

const { RangePicker } = DatePicker;

interface AddDataPickerModalProps {
  open: boolean;
  onCancel: () => void;
  onOk: (selectedData: any[]) => void;
  // 新增全部添加回调
  onAddAll?: (filterParams: {
    work_mode?: string;
    version_num?: string;
    station?: string;
    track_num_turns__gte?: string;
    track_num_turns__lte?: string;
    collection_time__gte?: string;
    collection_time__lte?: string;
    archive_time__gte?: string;
    archive_time__lte?: string;
    data_level?: string;
    data_key?: string;
  }) => void;
}

const AddDataPickerModal: React.FC<AddDataPickerModalProps> = ({ open, onCancel, onOk, onAddAll }) => {
  const [treeSelected, setTreeSelected] = useState<string[]>([]);
  const [dataKey, setDataKey] = useState<string>('');
  const [form] = Form.useForm();
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [dataLevels, setDataLevels] = useState<Array<{ key: string; label: string; count: number; size: string }>>([]);
  const [versionOptions, setVersionOptions] = useState<string[]>([]);
  const [stationOptions, setStationOptions] = useState<string[]>([]);
  const [workModeOptions, setWorkModeOptions] = useState<string[]>([]);
  const [dataLevel, setDataLevel] = useState('');
  const [tableData, setTableData] = useState<any[]>([]);
  const [treeDataState, setTreeDataState] = useState<DataNode[]>([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [tableLoading, setTableLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [sortState, setSortState] = useState<{
    field: string | null;
    order: 'ascend' | 'descend' | null;
  }>({
    field: null,
    order: null
  });
  const [filterParams, setFilterParams] = useState<{
    work_mode?: string;
    version_num?: string;
    station?: string;
    track_num_turns__gte?: string;
    track_num_turns__lte?: string;
    collection_time__gte?: string;
    collection_time__lte?: string;
    archive_time__gte?: string;
    archive_time__lte?: string;
  }>({});
  const tableContainerRef = useRef<HTMLDivElement>(null);
  const [tableScrollY, setTableScrollY] = useState<number>(0);

  const defaultColumns = [
    { title: '文件名', dataIndex: 'file_name', key: 'file_name', width: 300, ellipsis: { showTitle: false } },
    { title: '数据大小(MB)', dataIndex: 'data_size', key: 'data_size', width: 140, sorter: true, sortDirections: ['ascend', 'descend'] as const, render: (value: number) => (value / 1024 / 1024).toFixed(2) },
    { title: '任务型号', dataIndex: 'task_type', key: 'task_type', width: 100, sorter: true, sortDirections: ['ascend', 'descend'] as const },
    { title: '载荷', dataIndex: 'dm_zhname', key: 'dm_zhname', width: 100, sorter: true, sortDirections: ['ascend', 'descend'] as const },
    { title: '数据级别', dataIndex: 'data_level', key: 'data_level', width: 100, sorter: true, sortDirections: ['ascend', 'descend'] as const },
    { title: '轨道圈数', dataIndex: 'track_num_turns', key: 'track_num_turns', width: 100, sorter: true, sortDirections: ['ascend', 'descend'] as const },
    { title: '采集开始时间', dataIndex: 'collection_time_start', key: 'collection_time_start', width: 180, sorter: true, sortDirections: ['ascend', 'descend'] as const },
    { title: '采集结束时间', dataIndex: 'collection_time_end', key: 'collection_time_end', width: 180, sorter: true, sortDirections: ['ascend', 'descend'] as const },
    { title: '归档时间', dataIndex: 'archive_time', key: 'archive_time', width: 180, sorter: true, sortDirections: ['ascend', 'descend'] as const }
  ];

  const [columns, setColumns] = useState(defaultColumns);

  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 42;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        (body as HTMLElement).style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => { window.removeEventListener('resize', calculateTableScrollHeight); };
  }, []);

  useEffect(() => { calculateTableScrollHeight(); }, [dataLevels]);

  const fetchDataLevel = async () => {
    try {
      if (!dataKey) return;
      const response = await request.get('/Management/DataLevel', { params: { data_key: dataKey, ...filterParams } });
      if (response.status === 200) {
        const { data_level } = response.data.data;
        const newDataLevels = data_level.map((item: any) => ({ key: item.level, label: item.level === '' ? '全部' : `${item.level}级`, count: item.count, size: `${(item.size / 1024 / 1024 / 1024).toFixed(2)}GB` }));
        setDataLevels(newDataLevels);
      }
    } catch (error: any) { message.error(error?.message || '获取数据等级信息失败'); }
  };

  const fetchFilterOptions = async () => {
    try {
      if (!dataKey) return;
      const response = await request.get('/Management/DataFilterOptions', { params: { data_key: dataKey, data_level: dataLevel } });
      if (response.status === 200) {
        const { work_modes, version_nums, station } = response.data.data;
        setWorkModeOptions(work_modes || []);
        setVersionOptions(version_nums || []);
        setStationOptions(station || []);
      }
    } catch (error: any) { message.error(error?.message || '获取筛选选项失败'); }
  };

  const fetchTableData = async () => {
    setTableLoading(true);
    try {
      if (!dataKey) return;
      const queryParams = { data_key: dataKey, ...filterParams, data_level: dataLevel, ordering: sortState.field ? `${sortState.order === 'descend' ? '-' : ''}${sortState.field}` : undefined, page: current, page_size: pageSize };
      const response = await request.get('/Management/DataList', { params: queryParams });
      if (response.status === 200) {
        const { list, count, page } = response.data.data;
        const formattedData = list.map((item: any) => ({ key: item.product_id, product_id: item.product_id, file_name: item.file_name, file_path: item.file_path, bk_pstate: item.bk_pstate, data_type: item.data_type, release_status: item.release_status, collection_time_start: item.collection_time_start, collection_time_end: item.collection_time_end, archive_time: item.archive_time, data_size: item.data_size, task_type: item.task_type, station: item.station, dm_zhname: item.dm_zhname, version_num: item.version_num, track_num_turns: item.track_num_turns, is_favorites: item.is_favorites }));
        setTableData(formattedData);
        setCurrent(page);
        setTotal(count);
      }
    } catch (error: any) { message.error(error?.message || '获取数据列表失败'); } finally { setTableLoading(false); }
  };

  const fetchTreeData = async () => {
    setTreeLoading(true);
    try {
      const response = await request.get(`/Management/DirectoryTree`, { params: { data_type: 1 } });
      if (response.status === 200) {
        const transformTreeData = (items: any[], level = 1): DataNode[] => items.map((item) => ({ title: item.name, key: item.value, className: level === 1 ? 'level-1-node' : level === 2 ? 'level-2-node' : '', children: item.children ? transformTreeData(item.children, level + 1) : [] }));
        const newTreeData = transformTreeData(response.data.data);
        setTreeDataState(newTreeData);
        let expanded: React.Key[] = [];
        if (newTreeData.length > 0) {
          expanded.push(newTreeData[0].key);
          const collectAllDescendantKeys = (nodes: DataNode[]): React.Key[] => {
            let keys: React.Key[] = [];
            nodes.forEach((node: DataNode) => {
              if (node.children && node.children.length > 0) {
                keys = keys.concat(node.children.map((child: DataNode) => child.key));
                keys = keys.concat(collectAllDescendantKeys(node.children));
              }
            });
            return keys;
          };
          if (newTreeData[0].children && newTreeData[0].children.length > 0) expanded = expanded.concat(collectAllDescendantKeys([newTreeData[0]]));
          for (let i = 1; i < newTreeData.length; i++) {
            const node = newTreeData[i];
            if (node?.children && node.children.length > 0) expanded = expanded.concat(collectAllDescendantKeys([node]));
          }
        }
        setExpandedKeys(expanded);
      }
    } catch (error: any) { message.error(error?.message || '加载树形数据失败'); } finally { setTreeLoading(false); }
  };

  useEffect(() => { fetchTreeData(); }, []);
  useEffect(() => { if (dataKey) { fetchDataLevel(); fetchFilterOptions(); setFilterParams({}); form.resetFields(); setCurrent(1); setDataLevel(''); } }, [dataKey]);
  useEffect(() => { if (dataKey) { fetchFilterOptions(); setCurrent(1); } }, [dataLevel]);
  useEffect(() => { if (dataKey) fetchTableData(); }, [current, pageSize, dataLevel, sortState, filterParams]);
  useEffect(() => { if (dataKey) fetchDataLevel(); }, [filterParams]);
  useEffect(() => { if (open) { fetchTreeData(); form.resetFields(); setCurrent(1); setDataLevel(''); setFilterParams({}); setSelectedRowKeys([]); } }, [open]);

  const isNodeSelectable = (node: DataNode, treeData: DataNode[]): boolean => {
    const isFirstLevel = treeData.some((firstLevelNode) => firstLevelNode.key === node.key);
    if (isFirstLevel) return false;
    const isSecondLevel = treeData.some((firstLevelNode) => firstLevelNode.children?.some((secondLevelNode) => secondLevelNode.key === node.key));
    if (isSecondLevel) return false;
    return true;
  };

  const getFirstSelectableNode = (nodes: DataNode[]): string | null => {
    for (const firstLevelNode of nodes) {
      if (firstLevelNode.children) {
        for (const secondLevelNode of firstLevelNode.children) {
          if (secondLevelNode.children && secondLevelNode.children.length > 0) return secondLevelNode.children[0].key as string;
        }
      }
    }
    return null;
  };

  const handleExpand = (keys: React.Key[], { expanded, node }: any) => {
    const isFirstLevel = treeDataState.some((firstLevelNode) => firstLevelNode.key === node.key);
    if (isFirstLevel) {
      const firstLevelKeys = treeDataState.map((n) => n.key);
      let newExpandedKeys;
      if (expanded) newExpandedKeys = [node.key, ...expandedKeys.filter((k) => !firstLevelKeys.includes(k) && k !== node.key)];
      else newExpandedKeys = expandedKeys.filter((k) => k !== node.key);
      setExpandedKeys(newExpandedKeys);
    } else {
      setExpandedKeys(keys);
    }
  };

  useEffect(() => {
    if (treeDataState.length > 0) {
      const firstSelectableKey = getFirstSelectableNode(treeDataState);
      if (firstSelectableKey) { setTreeSelected([firstSelectableKey]); setDataKey(firstSelectableKey); }
    }
  }, [treeDataState]);

  const rowSelection = { selectedRowKeys, columnWidth: 50, onChange: (keys: React.Key[]) => setSelectedRowKeys(keys) };

  const onFinish = (values: any) => {
    if (values.collection_time_range) {
      values.collection_time__gte = values.collection_time_range[0]?.format('YYYY-MM-DD 00:00:00');
      values.collection_time__lte = values.collection_time_range[1]?.format('YYYY-MM-DD 23:59:59');
      delete values.collection_time_range;
    }
    if (values.archive_time_range) {
      values.archive_time__gte = values.archive_time_range[0]?.format('YYYY-MM-DD 00:00:00');
      values.archive_time__lte = values.archive_time_range[1]?.format('YYYY-MM-DD 23:59:59');
      delete values.archive_time_range;
    }
    setCurrent(1);
    setFilterParams(values);
  };

  const handleOk = () => {
    const selectedData = tableData.filter((item) => selectedRowKeys.includes(item.key));
    onOk(selectedData);
  };

  // 全部添加功能
  const handleAddAll = () => {
    if (!dataKey) {
      message.error('请先选择数据集');
      return;
    }

    if (!onAddAll) {
      message.error('全部添加功能未配置');
      return;
    }

    // 构造筛选参数，不包含planet_id
    const allFilterParams = {
      ...filterParams,
      data_level: dataLevel,
      data_key: dataKey
    };

    // 调用父组件的全部添加回调
    onAddAll(allFilterParams);
  };

  return (
    <Modal title="添加数据" open={open} onCancel={onCancel} width={'90%'} styles={{ body: { height: 'calc(100vh - 200px)', overflow: 'hidden' } }} style={{ top: 50, bottom: 50 }} footer={null}>
      <div style={{ display: 'flex', gap: '16px', height: '100%' }}>
        <div className="add-data-modal-tree-container" style={{ width: '300px', flexShrink: 0, background: '#fafafa', borderRadius: '3px', padding: '5px', overflow: 'auto' }}>
          <Spin spinning={treeLoading}>
            <Tree
              blockNode
              treeData={treeDataState}
              expandedKeys={expandedKeys}
              onExpand={handleExpand}
              selectedKeys={treeSelected}
              onSelect={(selectedKeys, info) => {
                if (selectedKeys.length === 0) return;
                const isSelectable = isNodeSelectable(info.node, treeDataState);
                if (isSelectable) { setTreeSelected(selectedKeys.map(String)); setDataKey(selectedKeys[0] as string); }
                else {
                  const nodeKey = info.node.key;
                  const isExpanded = expandedKeys.includes(nodeKey);
                  if (isExpanded) setExpandedKeys(expandedKeys.filter((key) => key !== nodeKey));
                  else setExpandedKeys([...expandedKeys, nodeKey]);
                  setTreeSelected([]);
                }
              }}
              style={{ minHeight: 100 }}
            />
          </Spin>
        </div>

        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
          <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
            <Form.Item name="version_num" label="版本号" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择版本号" style={{ width: '100%' }}>
                {versionOptions.map((option) => (<Select.Option key={option} value={option}>{option}</Select.Option>))}
              </Select>
            </Form.Item>
            <Form.Item name="work_mode" label="工作模式" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择工作模式" style={{ width: '100%' }}>
                {workModeOptions.map((option) => (<Select.Option key={option} value={option}>{option}</Select.Option>))}
              </Select>
            </Form.Item>
            <Form.Item name="station" label="接收站" style={{ width: 320 }}>
              <Select allowClear placeholder="请选择接收站" style={{ width: '100%' }}>
                {stationOptions.map((option) => (<Select.Option key={option} value={option}>{option}</Select.Option>))}
              </Select>
            </Form.Item>
            <Form.Item label="采集时间" style={{ width: 320 }} name="collection_time_range">
              <RangePicker style={{ width: '100%' }} placeholder={["开始时间", "结束时间"]} />
            </Form.Item>
            <Form.Item label="归档时间" style={{ width: 320 }} name="archive_time_range">
              <RangePicker style={{ width: '100%' }} placeholder={["开始时间", "结束时间"]} />
            </Form.Item>
            <Form.Item 
              label="轨道圈数/探测周期编号" 
              style={{ 
                width: 320,
                '--ant-form-item-label-width': '160px'
              } as React.CSSProperties}
            >
              <Space style={{ width: '100%' }}>
                <Form.Item name="track_num_turns__gte" noStyle style={{ flex: 1 }}>
                  <Input type="number" placeholder="起始" style={{ width: '70px' }} min={0} />
                </Form.Item>
                <span style={{ color: '#999' }}>—</span>
                <Form.Item name="track_num_turns__lte" noStyle style={{ flex: 1 }}>
                  <Input type="number" placeholder="结束" style={{ width: '70px' }} min={0} />
                </Form.Item>
              </Space>
            </Form.Item>
            <Form.Item style={{ paddingLeft: 80, width: 320 }}>
              <Space>
                <Button type="primary" htmlType="submit">筛选</Button>
                <Button htmlType="button" onClick={() => form.resetFields()}>清除</Button>
              </Space>
            </Form.Item>
          </Form>

          <div className="fixed-filter-tabs">
            {dataLevels.map((tab) => (
              <span key={tab.key} className={`filter-tab-item${dataLevel === tab.key ? ' active' : ''}`} onClick={() => setDataLevel(tab.key)}>
                {tab.label}({tab.count}/{tab.size})
              </span>
            ))}
          </div>

          <div ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
            <DraggableTable
              rowSelection={rowSelection}
              columns={columns}
              dataSource={tableData}
              pagination={false}
              tableLayout="fixed"
              style={{ flex: 1 }}
              scroll={{ y: tableScrollY, x: 'max-content' }}
              bordered
              size="小"
              loading={tableLoading}
              rowClassName={(_: any, index: number) => (index % 2 === 0 ? 'zebra-row-odd' : 'zebra-row-even')}
              onChange={(_: any, __: any, sorter: any) => { if (sorter.field) setSortState({ field: sorter.field, order: sorter.order }); }}
              onColumnsChange={(newColumns) => setColumns(newColumns)}
            />
          </div>

          <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Space>
              <Button type="primary" onClick={handleOk} disabled={selectedRowKeys.length === 0}>添加数据</Button>
              {onAddAll && (
                <Button 
                  type="primary" 
                  onClick={handleAddAll} 
                  disabled={!dataKey}
                >
                  全部添加
                </Button>
              )}
            </Space>
            <Pagination current={current} pageSize={pageSize} total={total} showSizeChanger pageSizeOptions={['10', '20', '50']} onChange={(page, size) => { setCurrent(page); setPageSize(size!); }} showTotal={(t) => `共 ${t} 条`} />
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default AddDataPickerModal;


